#!/bin/bash

# JSON文件转换脚本
# 用于将包含双重编码JSON字符串的txt文件转换为标准JSON文件

set -e

# 颜色定义
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 项目根目录
PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$PROJECT_DIR"

echo -e "${BLUE}JSON文件转换工具${NC}"
echo "========================================"

# 构建classpath
CLASSPATH="target/classes"
CLASSPATH="$CLASSPATH:$HOME/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.11.4/jackson-databind-2.11.4.jar"
CLASSPATH="$CLASSPATH:$HOME/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.11.4/jackson-core-2.11.4.jar"
CLASSPATH="$CLASSPATH:$HOME/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.11.4/jackson-annotations-2.11.4.jar"
CLASSPATH="$CLASSPATH:$HOME/.m2/repository/log4j/log4j/1.2.12/log4j-1.2.12.jar"

# 检查是否已编译
if [ ! -d "target/classes" ]; then
    echo -e "${BLUE}正在编译项目...${NC}"
    mvn compile -q
    echo -e "${GREEN}✓ 编译完成${NC}"
fi

# 根据参数决定转换方式
if [ $# -eq 0 ]; then
    # 默认：转换三个问题文件
    echo -e "${BLUE}转换三个问题文件到 src/main/resources/json/${NC}"
    echo "========================================" 
    
    mkdir -p src/main/resources/json
    
    echo -e "${BLUE}[1/3] 转换 DHF 文件...${NC}"
    java -cp "$CLASSPATH" tech.waterism.util.JsonFileConverter file \
        "src/main/resources/20800900-方案179-DHF-1762739817729-20250605080000.txt" \
        "src/main/resources/json/DHF-input.json"
    
    echo -e "${BLUE}[2/3] 转换 LAG 文件...${NC}"
    java -cp "$CLASSPATH" tech.waterism.util.JsonFileConverter file \
        "src/main/resources/20810200-方案178-LAG_3-1762739718359-20250605080000.txt" \
        "src/main/resources/json/LAG-input.json"
    
    echo -e "${BLUE}[3/3] 转换 SMS_3 文件...${NC}"
    java -cp "$CLASSPATH" tech.waterism.util.JsonFileConverter file \
        "src/main/resources/20810200-方案178-SMS_3-1762739718330-20250605080000.txt" \
        "src/main/resources/json/SMS_3-input.json"
    
    echo "========================================"
    echo -e "${GREEN}✓ 全部完成！转换后的文件位于:${NC}"
    echo "  • src/main/resources/json/DHF-input.json"
    echo "  • src/main/resources/json/LAG-input.json"
    echo "  • src/main/resources/json/SMS_3-input.json"
    
elif [ "$1" = "file" ]; then
    # 转换单个文件
    if [ $# -lt 3 ]; then
        echo -e "${RED}错误: 文件模式需要指定输入文件和输出文件${NC}"
        echo "用法: $0 file <输入文件.txt> <输出文件.json>"
        exit 1
    fi
    
    java -cp "$CLASSPATH" tech.waterism.util.JsonFileConverter file "$2" "$3"
    
elif [ "$1" = "dir" ]; then
    # 转换整个目录
    if [ $# -lt 3 ]; then
        echo -e "${RED}错误: 目录模式需要指定输入目录和输出目录${NC}"
        echo "用法: $0 dir <输入目录> <输出目录>"
        exit 1
    fi
    
    java -cp "$CLASSPATH" tech.waterism.util.JsonFileConverter dir "$2" "$3"
    
else
    echo "用法:"
    echo "  $0                          # 转换三个问题文件（默认）"
    echo "  $0 file <输入.txt> <输出.json>  # 转换单个文件"
    echo "  $0 dir <输入目录> <输出目录>   # 批量转换目录"
    exit 1
fi

